﻿using System;
using System.ComponentModel;
using NerdWare.Crm2011VsTools.DataModel;
using NerdWare.Crm2011VsTools.DialogPages;
using NerdWare.Crm2011VsTools.Globals;

namespace NerdWare.Crm2011VsTools.ViewModel
{
    class ScriptInjectorViewModel : INotifyPropertyChanged, IDisposable
    {
        private readonly ScriptInjectorModel _scriptInjectorModel;

        public ScriptInjectorViewModel()
        {
            _scriptInjectorModel = new ScriptInjectorModel();
            IsRunning = _scriptInjectorModel.Proxy.IsRunning;
        }

        public void FlipOnOff(CrmServerConnection crmServerConnection)
        {
            if (this._scriptInjectorModel.Proxy.IsRunning)
            {
                this._scriptInjectorModel.Proxy.StopProxy();
                this.IsRunning = false;
                Logger.Output.Log("Fiddler Core stopped.");
            }
            else
            {
                this._scriptInjectorModel.Proxy.StartProxy(
                    crmServerConnection.Type, 
                    crmServerConnection.Server, 
                    crmServerConnection.Port,
                    crmServerConnection.Organization,
                    Options.GeneralSetting.FiddlerPort,
                    crmServerConnection.UseCustomFolder ? crmServerConnection.ScriptFolder : Options.GeneralSetting.GlobalScriptFolder);
                this.IsRunning = true;
                Logger.Output.Log("Fiddler Core started listening on Server '{0}' for Organization '{1}'", crmServerConnection.Server, crmServerConnection.Organization);
            }
        }


        private bool _isRunning;
        public bool IsRunning
        {
            get { return _isRunning; }
            set
            {
                _isRunning = value;
                this.RaisePropertyChanged("RunningStatus");
            }
        }

        private string _runningStatus;
        public string RunningStatus
        {
            get { return _scriptInjectorModel.Proxy.IsRunning ? "Is Running" : "Is not Running"; }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void RaisePropertyChanged(string property)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(property));
            }
        }

        #region Implementation of IDisposable

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        /// <filterpriority>2</filterpriority>
        public void Dispose()
        {
            if (_scriptInjectorModel != null)
                _scriptInjectorModel.Dispose();
        }

        #endregion
    }
}
